package com.captain.special.二叉树.简单;

import com.captain.leetcode.TreeNode;

/**
 * Des:
 *
 * @author XL
 * @Date 2022/5/6 23:17
 */
public class 二叉搜索树的最近公共祖先235 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode ancestor = root;
        //二叉搜索树 节点值 > 左节点  < 右节点
        while (true) {
            if (p.val < ancestor.val && q.val < ancestor.val) {
                ancestor = ancestor.left;
            } else if (p.val > ancestor.val && q.val > ancestor.val) {
                ancestor = ancestor.right;
            } else {
                break;
            }
        }
        return ancestor;
    }
}
